package com.lemon.boot.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.lemon.boot.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 李猛
 * @datetime 2023/11/6 16:59
 * @description 类对象
 */
@Slf4j
public final class ResponseUtil {
    /**
     * Http 响应失败方法
     *
     * @param response
     * @param code
     * @param message
     * @return
     */
    public static void fail(HttpServletResponse response, int code, String message) {
        Result<String> result = Result.fail(code, message);
        String json = JSONUtil.toJsonStr(result);
        json(response, json);
    }

    /**
     * Http 响应失败方法
     *
     * @param response
     * @param status
     * @return
     */
    public static void fail(HttpServletResponse response, HttpStatus status) {
        Result<String> result = Result.fail(status.value(), status.getReasonPhrase());
        String json = JSONUtil.toJsonStr(result);
        json(response, json);
    }

    /**
     * Http 响应成功的方法
     *
     * @param response
     * @param message
     * @return
     */
    public static void success(HttpServletResponse response, String message) {
        Result<String> result = Result.ok(message);
        String json = JSONUtil.toJsonStr(result);
        json(response, json);
    }

    /**
     * Http 响应JSON的方法
     *
     * @param response
     * @param json
     * @return
     */
    public static void json(HttpServletResponse response, String json) {
        //设置响应类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.write(json);
        } catch (Exception e) {
            log.error("ResponseUtil.json.message:{}", e.getMessage());
        }
    }

    /**
     * Http 响应bytes的方法
     *
     * @param response
     * @param bytes
     * @return
     */
    public static void bytes(HttpServletResponse response, byte[] bytes) {
        //设置响应类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.IMAGE_PNG_VALUE);

        try (ServletOutputStream stream = response.getOutputStream()) {
            stream.write(bytes);
        } catch (Exception e) {
            log.error("ResponseUtil.bytes.message:{}", e.getMessage());
        }
    }
}
